package com.etc.threaddemo.lock;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: knowno
 * @create: 2024-09-13 11:05
 * @Version 1.0
 * <p>
 * 非线程安全
 **/
public class TestArrayList4 {
    public static void main(String[] args) throws InterruptedException {

        ArrayList<String> list = new ArrayList<>();

        //1. 创建一个ReentrantLock对象
        ReentrantLock reentrantLock = new ReentrantLock();

        //循环执行50000
        for (int i = 1; i <= 50000; i++) {

            //创建一个线程对象，将Thread.name添加到集合中来
            new Thread(() -> {
                //2 .获得锁
                reentrantLock.lock();
                list.add(Thread.currentThread().getName());

                //3 释放锁
                reentrantLock.unlock();
            }).start();
        }
        //休眠主线程
        Thread.sleep(20000);

        System.out.println("list.size(): " + list.size());

    }
}
